package admin

import (
	"config-client-v1/model"
	"config-client-v1/utils/tools"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"strconv"
)

type PageController struct {
}

func (con PageController) List(ctx *gin.Context) {
	userToken := GetUserToken(ctx)
	param := struct {
		GroupID  int    `json:"group_id"`
		PageName string `json:"page_name"`
		model.QueryData
	}{}
	err := ctx.ShouldBindBodyWith(&param, binding.JSON)
	if err != nil {
		ctx.JSON(200, gin.H{
			"code":    2,
			"message": "无效的参数",
			"data":    err.Error(),
		})
		return
	}

	tx := model.DB.Where("del = 0").Where("project_id = ?", userToken.ProjectID)
	if param.GroupID != 0 {
		tx.Where("group_id = ?", param.GroupID)
	}
	if param.PageName != "" {
		tx.Where("page_name like ?", "%"+param.PageName+"%")
	}
	var count int64
	list := make([]model.Page, 0)
	err = tx.Model(&model.Page{}).Count(&count).Error
	if err != nil {
		ctx.JSON(200, gin.H{
			"code":    6,
			"message": err.Error(),
		})
		return
	}

	err = tx.Order("id desc").Offset(param.StartPage()).Limit(param.PageSize).Find(&list).Error
	if err != nil {
		ctx.JSON(200, gin.H{
			"code":    6,
			"message": err.Error(),
		})
		return
	}

	ctx.JSON(200, gin.H{
		"code":    0,
		"message": "success",
		"data": map[string]interface{}{
			"list":  list,
			"count": count,
		},
	})
}

func (con PageController) Save(ctx *gin.Context) {
	param := struct {
		Id            int    `json:"id"`
		GroupID       int    `json:"group_id" binding:"required"`
		PageAttribute int    `json:"page_attribute" binding:"required"`
		PageName      string `json:"page_name" binding:"required,max=30"`
		Content       string `json:"content" binding:"required"`
		ContentCeshi  string `json:"content_ceshi"`
		Canvas        string `json:"canvas" binding:"required"`
		ExpData       string `json:"exp_data"`
		SeriesColors  string `json:"seriesColors"`
		ReportType    int    `json:"report_type"`
		IsDefault     uint8  `json:"is_default"`
	}{}
	err := ctx.ShouldBindBodyWith(&param, binding.JSON)
	if err != nil {
		ctx.JSON(200, gin.H{
			"code":    2,
			"message": "无效的参数",
			"data":    err.Error(),
		})
		return
	}

	groupExist := &model.PageGroup{}

	exist, err := groupExist.Exists(param.GroupID)
	if !exist {
		ctx.JSON(200, gin.H{
			"code":    2,
			"message": "无效的参数 group_id",
			"data":    err,
		})
		return
	}

	data := model.Page{}
	data.ProjectID = groupExist.ProjectID
	data.GroupID = param.GroupID
	data.PageAttribute = param.PageAttribute
	data.PageName = param.PageName
	data.Content = param.Content
	data.Canvas = param.Canvas
	data.ExpData = param.ExpData
	data.SeriesColors = param.SeriesColors
	data.ReportType = param.ReportType
	data.ContentCeshi = ""
	now := tools.GetNow()
	if param.Id == 0 {
		data.CreateTime = &now
		data.UpdateTime = &now
		if param.IsDefault == 0 {
			data.IsDefault = 0
		} else {
			data.IsDefault = 1
			_ = model.DB.Model(&model.Page{}).Where("1=1").Update("is_default", 0).Error
		}
		err = model.DB.Create(&data).Error
	} else {
		page := &model.Page{}
		pageExist, err2 := page.Exists(param.Id)
		if !pageExist {
			ctx.JSON(200, gin.H{
				"code":    2,
				"message": "无效的id",
				"data":    err2,
			})
			return
		}

		data.UpdateTime = &now
		if param.IsDefault == 0 {
			data.IsDefault = 0
		} else {
			data.IsDefault = 1
			_ = model.DB.Model(&model.Page{}).Where("1=1").Update("is_default", 0).Error
		}
		err = model.DB.Model(&model.Page{}).Where("id = ?", param.Id).
			Select("project_id", "group_id", "page_attribute", "page_name", "content", "content_ceshi", "canvas", "canvas", "exp_data", "seriesColors", "report_type", "is_default").
			Updates(&data).Error
	}

	if err != nil {
		ctx.JSON(200, gin.H{
			"code":    6,
			"message": err.Error(),
		})
		return
	}
	//_ = data.ParseExpData()
	model.LoadRunningExpPage(data.ProjectID)
	ctx.JSON(200, gin.H{
		"code":    0,
		"message": "success",
		"data":    map[string]interface{}{},
	})
}

func (con PageController) SetDefault(ctx *gin.Context) {
	param := struct {
		Id        int   `json:"id" binding:"required"`
		IsDefault uint8 `json:"is_default" binding:"required"`
	}{}
	err := ctx.ShouldBindBodyWith(&param, binding.JSON)
	if err != nil {
		ctx.JSON(200, gin.H{
			"code":    2,
			"message": "无效的参数",
			"data":    err.Error(),
		})
		return
	}
	info := model.Page{}
	err = model.DB.Model(&model.Page{}).Where("id = ?", param.Id).First(&info).Error
	if err != nil {
		ctx.JSON(200, gin.H{
			"code":    6,
			"message": err.Error(),
		})
		return
	}

	if param.IsDefault == 0 {
		_ = model.DB.Model(&model.Page{}).Where("id = ?", param.Id).Update("is_default", 0).Error
	} else {
		_ = model.DB.Model(&model.Page{}).Where("1=1").Update("is_default", 0).Error
		_ = model.DB.Model(&model.Page{}).Where("id = ?", param.Id).Update("is_default", 1).Error
	}

	ctx.JSON(200, gin.H{
		"code":    0,
		"message": "success",
		"data":    map[string]interface{}{},
	})
}
func (con PageController) Detail(ctx *gin.Context) {
	param := struct {
		Id int `json:"id" binding:"required"`
	}{}
	if ctx.Request.Method == "POST" {
		err := ctx.ShouldBindBodyWith(&param, binding.JSON)
		if err != nil {
			ctx.JSON(200, gin.H{
				"code":    2,
				"message": "无效的参数",
				"data":    err.Error(),
			})
			return
		}
	} else {
		queryID := ctx.Query("id")
		param.Id, _ = strconv.Atoi(queryID)
	}

	info := model.Page{}

	err := model.DB.Model(&model.Page{}).Where("id = ?", param.Id).First(&info).Error
	if err != nil {
		ctx.JSON(200, gin.H{
			"code":    6,
			"message": err.Error(),
		})
		return
	}

	ctx.JSON(200, gin.H{
		"code":    0,
		"message": "success",
		"data": map[string]interface{}{
			"info": info,
		},
	})
}

func (con PageController) Delete(ctx *gin.Context) {
	param := struct {
		Id int `json:"id" binding:"required"`
	}{}
	err := ctx.ShouldBindBodyWith(&param, binding.JSON)
	if err != nil {
		ctx.JSON(200, gin.H{
			"code":    2,
			"message": "无效的参数",
			"data":    err.Error(),
		})
		return
	}
	info := model.Page{}
	err = model.DB.Where("id = ?", param.Id).First(&info).Error
	if err != nil {
		ctx.JSON(200, gin.H{
			"code":    6,
			"message": err.Error(),
		})
		return
	}
	err = model.DB.Where("id = ?", param.Id).Delete(&model.Page{}).Error
	if err != nil {
		ctx.JSON(200, gin.H{
			"code":    6,
			"message": err.Error(),
		})
		return
	}
	ctx.JSON(200, gin.H{
		"code":    0,
		"message": "success",
		"data":    map[string]interface{}{},
	})
}

func (con PageController) Copy(ctx *gin.Context) {
	param := struct {
		OriginPageID int    `json:"origin_page_id" binding:"required"`
		ToGroupID    int    `json:"to_group_id" binding:"required"`
		PageName     string `json:"page_name" binding:"required,max=30"`
	}{}
	err := ctx.ShouldBindBodyWith(&param, binding.JSON)
	if err != nil {
		ctx.JSON(200, gin.H{
			"code":    2,
			"message": "无效的参数",
			"data":    err.Error(),
		})
		return
	}
	originPage := model.Page{}
	err = model.DB.Model(&model.Page{}).Where("id = ?", param.OriginPageID).Limit(1).Find(&originPage).Error
	if err != nil {
		ctx.JSON(200, gin.H{
			"code":    6,
			"message": err.Error(),
		})
		return
	}
	if originPage.ID == 0 {
		ctx.JSON(200, gin.H{
			"code":    2,
			"message": "无效的参数 origin_page_id",
		})
		return
	}
	group := model.PageGroup{}
	err = model.DB.Model(&model.PageGroup{}).Where("id = ?", param.ToGroupID).Limit(1).Find(&group).Error
	if err != nil {
		ctx.JSON(200, gin.H{
			"code":    6,
			"message": err.Error(),
		})
		return
	}
	if group.ID == 0 {
		ctx.JSON(200, gin.H{
			"code":    2,
			"message": "无效的参数 to_group_id",
		})
		return
	}

	now := tools.GetNow()
	originPage.ID = 0
	originPage.PageName = param.PageName
	originPage.OriginID = param.OriginPageID
	originPage.GroupID = param.ToGroupID
	originPage.CreateTime = &now
	originPage.UpdateTime = &now

	err = model.DB.Create(&originPage).Error
	if err != nil {
		ctx.JSON(200, gin.H{
			"code":    6,
			"message": err.Error(),
		})
		return
	}
	ctx.JSON(200, gin.H{
		"code":    0,
		"message": "success",
		"data":    map[string]interface{}{},
	})
}

func (con PageController) ReportFormSave(ctx *gin.Context) {
	userToken := GetUserToken(ctx)
	param := model.PageReportForm{}
	err := ctx.ShouldBindBodyWith(&param, binding.JSON)
	if err != nil {
		ctx.JSON(200, gin.H{
			"code":    2,
			"message": "无效的参数",
			"data":    err.Error(),
		})
		return
	}

	pageExist := &model.Page{}
	exist, err := pageExist.Exists(param.PageID)
	if !exist {
		ctx.JSON(200, gin.H{
			"code":    2,
			"message": "无效的参数 page_id",
			"data":    err,
		})
		return
	}
	param.PageGroupID = pageExist.GroupID

	now := tools.GetNow()
	if param.ID == 0 {
		param.CreateTime = &now
		param.UpdateTime = &now
		param.ProjectID = userToken.ProjectID
		err = model.DB.Create(&param).Error
		if err != nil {
			ctx.JSON(200, gin.H{
				"code":    6,
				"message": err.Error(),
			})
			return
		}
	} else {
		old := &model.PageReportForm{}
		exist, err = old.Exists(param.ID)
		if !exist {
			ctx.JSON(200, gin.H{
				"code":    2,
				"message": "无效的参数 id",
				"data":    err,
			})
			return
		}
		param.UpdateTime = &now
		err = model.DB.Model(&model.PageReportForm{}).Where("id = ?", param.ID).Select("*").Omit("project_id", "create_time").Updates(&param).Error
		if err != nil {
			ctx.JSON(200, gin.H{
				"code":    6,
				"message": err.Error(),
			})
			return
		}

	}

	if err != nil {
		ctx.JSON(200, gin.H{
			"code":    6,
			"message": err.Error(),
		})
		return
	}

	ctx.JSON(200, gin.H{
		"code":    0,
		"message": "success",
		"data":    map[string]interface{}{},
	})
}

func (con PageController) ReportFormList(ctx *gin.Context) {
	userToken := GetUserToken(ctx)
	param := struct {
		PageID int `json:"page_id" binding:"required"`
	}{}
	err := ctx.ShouldBindBodyWith(&param, binding.JSON)
	if err != nil {
		ctx.JSON(200, gin.H{
			"code":    2,
			"message": "无效的参数",
			"data":    err.Error(),
		})
		return
	}
	list := make([]*model.PageReportForm, 0)
	err = model.DB.Model(&model.PageReportForm{}).Where("project_id = ? AND page_id = ?", userToken.ProjectID, param.PageID).Find(&list).Error
	if err != nil {
		ctx.JSON(200, gin.H{
			"code":    6,
			"message": err.Error(),
		})
		return
	}
	ctx.JSON(200, gin.H{
		"code":    0,
		"message": "success",
		"data": map[string]interface{}{
			"list": list,
		},
	})
}

func (con PageController) ComboSave(ctx *gin.Context) {
	userToken := GetUserToken(ctx)
	param := struct {
		Id      int    `json:"id"`
		Name    string `gorm:"column:name" json:"name" binding:"required,max=30"`
		Content string `gorm:"column:content" json:"content"`
	}{}
	err := ctx.ShouldBindBodyWith(&param, binding.JSON)
	if err != nil {
		ctx.JSON(200, gin.H{
			"code":    2,
			"message": "无效的参数",
			"data":    err.Error(),
		})
		return
	}
	now := tools.GetNow()
	data := model.ComboBox{}
	data.ProjectID = userToken.ProjectID
	data.UID = userToken.Uid
	data.Name = param.Name
	data.Content = param.Content
	if param.Id == 0 {
		data.CreateTime = &now
		nameExist := model.ComboBox{}
		err = model.DB.Where("project_id = ? AND name = ?", userToken.ProjectID, param.Name).Limit(1).Find(&nameExist).Error
		if err != nil {
			ctx.JSON(200, gin.H{
				"code":    6,
				"message": err.Error(),
			})
			return
		}
		if nameExist.ID != 0 {
			ctx.JSON(200, gin.H{
				"code":    2,
				"message": "组合框名称已存在",
				"data":    map[string]interface{}{},
			})
			return
		}
		err = model.DB.Create(&data).Error
	} else {
		old := &model.ComboBox{}
		pageExist, err2 := old.Exists(param.Id)
		if !pageExist {
			ctx.JSON(200, gin.H{
				"code":    2,
				"message": "无效的id",
				"data":    err2,
			})
			return
		}
		nameExist := model.ComboBox{}
		err = model.DB.Where("id != ? AND project_id = ? AND name = ?", param.Id, userToken.ProjectID, param.Name).Limit(1).Find(&nameExist).Error
		if err != nil {
			ctx.JSON(200, gin.H{
				"code":    6,
				"message": err.Error(),
			})
			return
		}
		if nameExist.ID != 0 {
			ctx.JSON(200, gin.H{
				"code":    2,
				"message": "组合框名称已存在",
				"data":    map[string]interface{}{},
			})
			return
		}
		err = model.DB.Model(&model.ComboBox{}).Where("id = ?", param.Id).Select("name", "content").Updates(&data).Error
	}
	if err != nil {
		ctx.JSON(200, gin.H{
			"code":    6,
			"message": err.Error(),
		})
		return
	}
	ctx.JSON(200, gin.H{
		"code":    0,
		"message": "success",
		"data":    map[string]interface{}{},
	})
}

func (con PageController) ComboList(ctx *gin.Context) {
	userToken := GetUserToken(ctx)
	param := struct {
		Name string `json:"name"`
	}{}
	err := ctx.ShouldBindBodyWith(&param, binding.JSON)
	if err != nil {
		ctx.JSON(200, gin.H{
			"code":    2,
			"message": "无效的参数",
			"data":    err.Error(),
		})
		return
	}

	tx := model.DB.Where("project_id = ?", userToken.ProjectID)
	if param.Name != "" {
		tx.Where("name like ?", "%"+param.Name+"%")
	}

	list := make([]model.ComboBox, 0)
	err = tx.Order("id desc").Find(&list).Error
	if err != nil {
		ctx.JSON(200, gin.H{
			"code":    6,
			"message": err.Error(),
		})
		return
	}

	ctx.JSON(200, gin.H{
		"code":    0,
		"message": "success",
		"data": map[string]interface{}{
			"list": list,
		},
	})
}
func (con PageController) ComboDelete(ctx *gin.Context) {
	param := struct {
		Id int `json:"id" binding:"required"`
	}{}
	err := ctx.ShouldBindBodyWith(&param, binding.JSON)
	if err != nil {
		ctx.JSON(200, gin.H{
			"code":    2,
			"message": "无效的参数",
			"data":    err.Error(),
		})
		return
	}
	err = model.DB.Model(&model.ComboBox{}).Where("id = ?", param.Id).Delete(&model.ComboBox{}).Error
	if err != nil {
		ctx.JSON(200, gin.H{
			"code":    6,
			"message": err.Error(),
		})
		return
	}
	ctx.JSON(200, gin.H{
		"code":    0,
		"message": "success",
		"data":    map[string]interface{}{},
	})
}

type CommonEquip struct {
	Name     string `json:"name"`
	Children []*CommonModel
}

type CommonModel struct {
	ModelName string `json:"model_name"`
	Content   string `json:"content"`
}

func (con PageController) AllModelList(ctx *gin.Context) {
	userToken := GetUserToken(ctx)
	param := struct {
		Name string `json:"name"`
	}{}
	err := ctx.ShouldBindBodyWith(&param, binding.JSON)
	if err != nil {
		ctx.JSON(200, gin.H{
			"code":    2,
			"message": "无效的参数",
			"data":    err.Error(),
		})
		return
	}
	fsModelList := make([]*model.FSModuleExt, 0)
	err = model.DB.Preload("FSEInfo").Where("project_id = ? AND code2 in ?", userToken.ProjectID, []string{"05", "06", "07", "08", "09", "10", "13"}).Find(&fsModelList).Error
	if err != nil {
		ctx.JSON(200, gin.H{
			"code":    6,
			"message": err.Error(),
			"data":    map[string]interface{}{},
		})
		return
	}
	canModelList := make([]*model.CANModelExt, 0)
	err = model.DB.Preload("PPEInfo").Where("project_id = ?", userToken.ProjectID).Find(&canModelList).Error
	if err != nil {
		ctx.JSON(200, gin.H{
			"code":    6,
			"message": err.Error(),
			"data":    map[string]interface{}{},
		})
		return
	}

	allFSName := make([]string, 0)
	for _, row := range fsModelList {
		if !tools.StrInArray(row.FSEInfo.Name, allFSName) {
			allFSName = append(allFSName, row.FSEInfo.Name)
		}
	}

	allPPEName := make([]string, 0)
	for _, row := range canModelList {
		if !tools.StrInArray(row.PPEInfo.Name, allPPEName) {
			allPPEName = append(allPPEName, row.PPEInfo.Name)
		}
	}

	list1 := make([]*CommonEquip, 0)
	for _, name := range allFSName {
		tmpEquip := &CommonEquip{Name: name}
		for _, row2 := range fsModelList {
			if row2.FSEInfo.Name == name {
				tmpEquip.Children = append(tmpEquip.Children, &CommonModel{ModelName: row2.ModuleName, Content: row2.JsonDetail})
			}
		}
		list1 = append(list1, tmpEquip)
	}

	list2 := make([]*CommonEquip, 0)
	for _, name := range allPPEName {
		tmpEquip := &CommonEquip{Name: name}
		for _, row2 := range canModelList {
			if row2.PPEInfo.Name == name {
				tmpEquip.Children = append(tmpEquip.Children, &CommonModel{ModelName: fmt.Sprintf("参数成组模块%d", row2.ID), Content: row2.Content})
			}
		}
		list2 = append(list2, tmpEquip)
	}

	ctx.JSON(200, gin.H{
		"code":    0,
		"message": "success",
		"data": map[string]interface{}{
			"fs_model_list":  list1,
			"can_model_list": list2,
		},
	})
}
